<script setup lang="ts">
import { uploadImageAPI } from '@/apis/consult';
import { timeOptions, flagOptions } from '@/constants'
import { useConsultStore } from '@/stores';
import type { ConsultIllnessForm, Image } from '@/types/consult';
import { showConfirmDialog, showFailToast, Toast, type UploaderAfterRead, type UploaderFileListItem } from 'vant';
import { computed, onMounted, ref } from 'vue';
import { useRouter } from 'vue-router';
defineOptions({
    name: 'ConsultIllness'
})

//定义表单的响应式数据
const form = ref<ConsultIllnessForm>({
    illnessDesc: '',
    illnessTime: undefined,
    consultFlag: undefined,
    pictures: []
})

// 保存上传的图片数据
const fileList = ref<Image[]>([])
// 图片超出大小要提示
const onOverSize = () => {
    showFailToast('图片超过')
}
// 删除文件预览时触发
const onDelete = (item: UploaderFileListItem) => {
    // TODO: 删除图片的时候
    //根据item 里面的某一属性 去form.value.pictures数组里面 找到对应被删除的元素
    form.value.pictures = form.value.pictures?.filter(
        (img: { url: string | undefined; }) => img.url === item.url
    )
}
// 文件读取完成后的回调函数
const onAfterRead: UploaderAfterRead = async (item) => {
    //TODO:文件读取完成后的回调函数
    if (Array.isArray(item)) return
    if (!item.file) return
    try {
        item.message = '上传中...'
        item.status = 'uploading'
        //开始上传
        const res = await uploadImageAPI(item.file)
        //给item 添加一个属性  就是为了删除图片的时候  将form.value.picutre 数组里面的对应的数据删除
        item.url = res.data.url
        //上传成功 需要将上传成功后图片的地址保存到form.pictures数组里面
        form.value.pictures?.push(res.data)
        item.message = ''
        item.status = 'done'
    } catch (error) {
        //上传失败
        item.message = '上传失败'
        item.status = 'failed'
    }
}
//通过计算属性来判断什么情况下需要给 van-button 按钮添加class="disabled"属性
const isDisabled = computed(() => {
    return (form.value.illnessDesc === '' || form.value.illnessTime === undefined || form.value.consultFlag === undefined)
})

const store = useConsultStore()
const router = useRouter()
// 下一步操作
const onNext = () => {
    if (form.value.illnessDesc === '') return showFailToast('请填写病情描述')
    if (form.value.illnessTime === undefined)
        return showFailToast('请选择患病时间')
    if (form.value.consultFlag === undefined)
        return showFailToast('请选择是否就诊过')
    store.setIllness(form.value)
    router.push('/user/patient?isChange=1')
}

onMounted(() => {
    //1.判断是否有数据 仓库里面
    if (store.consult.illnessDesc) {
        //2.显示确定弹出框
        showConfirmDialog({
            title: '温馨提示',
            message: '是否恢复您之前填写的病情信息呢？',
            closeOnPopstate: false
        }).then(() => {
            form.value.illnessDesc = store.consult.illnessDesc
            form.value.illnessTime = store.consult.illnessTime
            form.value.consultFlag = store.consult.consultFlag
            form.value.pictures = store.consult.pictures
            fileList.value = store.consult.pictures || []
        })
    }

})
</script>

<template>
    <div class="consult-illness-page">
        <cp-nav-bar title="图文问诊" />
        <!-- 医生提示 -->
        <div class="illness-tip van-hairline--bottom">
            <img class="img" src="@/assets/avatar-doctor.svg" />
            <div class="info">
                <p class="tit">在线医生</p>
                <p class="tip">
                    请描述你的疾病或症状、是否用药、就诊经历，需要我听过什么样的帮助
                </p>
                <p class="safe">
                    <cp-icon name="consult-safe" /><span>内容仅医生可见</span>
                </p>
            </div>
        </div>
        <!-- 表单 -->
        <div class="illness-form">
            <van-field type="textarea" rows="3" placeholder="请详细描述您的病情，病情描述不能为空" v-model="form.illnessDesc"></van-field>
            <div class="item">
                <p>本次患病多久了？</p>
                <CpRadioBtn :options="timeOptions" v-model="form.illnessTime"></CpRadioBtn>
            </div>
            <div class="item">
                <p>此次病情是否去医院就诊过？</p>
                <CpRadioBtn :options="flagOptions" v-model="form.consultFlag"></CpRadioBtn>
            </div>
            <div class="illness-img">
                <van-uploader v-model="fileList" upload-icon="photo-o" upload-text="上传图片" max-count="9"
                    :max-size="5 * 1024 * 1024" :after-read="onAfterRead" @oversize="onOverSize"
                    @delete="onDelete"></van-uploader>
                <p class="tip" v-if="!fileList.length">上传内容仅医生可见,最多9张图,最大5MB</p>
            </div>
            <van-button type="primary" block round :class="{ disabled: isDisabled }" @click="onNext">下一步</van-button>
        </div>

    </div>
</template>

<style lang="scss" scoped>
.consult-illness-page {
    padding-top: 46px;
}

.illness-tip {
    display: flex;
    padding: 15px;

    .img {
        width: 52px;
        height: 52px;
        border-radius: 4px;
        overflow: hidden;
        margin-top: 10px;
    }

    .info {
        flex: 1;
        padding-left: 12px;

        .tit {
            font-size: 16px;
            margin-bottom: 5px;
        }

        .tip {
            padding: 12px;
            background: var(--cp-bg);
            color: var(--cp-text3);
            font-size: 13px;
            margin-bottom: 10px;
        }

        .safe {
            font-size: 10px;
            color: var(--cp-text3);
            display: flex;
            align-items: center;

            .cp-icon {
                font-size: 12px;
                margin-right: 2px;
            }
        }
    }
}

.illness-form {
    padding: 15px;

    .van-field {
        padding: 0;

        &::after {
            border-bottom: none;
        }
    }

    .item {
        >p {
            color: var(--cp-text3);
            padding: 15px 0;
        }
    }
}

.illness-img {
    padding-top: 16px;
    margin-bottom: 40px;
    display: flex;
    align-items: center;

    .tip {
        font-size: 12px;
        color: var(--cp-tip);
    }

    ::v-deep() {
        .van-uploader {
            &__preview {
                &-delete {
                    left: -6px;
                    top: -6px;
                    border-radius: 50%;
                    background-color: var(--cp-primary);
                    width: 20px;
                    height: 20px;

                    &-icon {
                        transform: scale(0.9) translate(-22%, 22%);
                    }
                }

                &-image {
                    border-radius: 8px;
                    overflow: hidden;
                }
            }

            &__upload {
                border-radius: 8px;
            }

            &__upload-icon {
                color: var(--cp-text3);
            }
        }
    }
}

.van-button {
    font-size: 16px;
    margin-bottom: 30px;

    &.disabled {
        opacity: 1;
        background: #fafafa;
        color: #d9dbde;
        border: #fafafa;
    }
}
</style>